const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const morgan = require('morgan');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

// 路由导入
const authRoutes = require('./routes/auth');
const articleRoutes = require('./routes/articles');
const userRoutes = require('./routes/users');
const qaRoutes = require('./routes/qa');

const app = express();

// CORS配置
const corsOptions = {
    origin: '*', // 允许所有来源访问
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true
};

// 中间件
app.use(cors(corsOptions));
app.use(express.json());
app.use(morgan('dev'));

// 基础路由
app.get('/', (req, res) => {
    res.json({ message: '博客API服务正在运行' });
});

// 健康检查
app.get('/health', (req, res) => {
    const health = {
        status: 'ok',
        timestamp: new Date(),
        mongodb: mongoose.connection.readyState === 1 ? 'connected' : 'disconnected',
        uptime: process.uptime()
    };
    res.json(health);
});

// MongoDB连接配置
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/blog';
let retryCount = 0;
const MAX_RETRIES = 10;

const connectWithRetry = async () => {
    try {
        await mongoose.connect(MONGODB_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            serverSelectionTimeoutMS: 5000,
            socketTimeoutMS: 10000,
            connectTimeoutMS: 5000,
            family: 4
        });
        console.log('MongoDB连接成功');
        retryCount = 0;
    } catch (err) {
        console.error('MongoDB连接失败:', err);
        retryCount++;
        
        if (retryCount < MAX_RETRIES) {
            const delay = Math.min(1000 * Math.pow(2, retryCount), 10000);
            console.log(`${delay/1000}秒后第${retryCount}次重试连接...`);
            setTimeout(connectWithRetry, delay);
        } else {
            console.error('达到最大重试次数，请检查MongoDB服务状态');
            process.exit(1);
        }
    }
};

// 启动数据库连接
connectWithRetry();

// 监听数据库连接事件
mongoose.connection.on('error', (err) => {
    console.error('MongoDB连接错误:', err);
});

mongoose.connection.on('disconnected', () => {
    console.log('MongoDB连接断开，尝试重新连接...');
    retryCount = 0;
    connectWithRetry();
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/articles', articleRoutes);
app.use('/api/users', userRoutes);
app.use('/api/qa', qaRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ 
        message: '服务器内部错误',
        error: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
});

// 404处理
app.use((req, res) => {
    res.status(404).json({ message: '请求的资源不存在' });
});

const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';

app.listen(PORT, HOST, () => {
    console.log(`服务器运行在 http://${HOST}:${PORT}`);
    console.log('环境:', process.env.NODE_ENV || 'development');
}); 